<template>
  <div class="novel-detail-container">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-left">
        <div class="logo">Draw-Evo</div>
      </div>
      <!--      <div class="navbar-center">-->
      <!--        <nav class="nav-links">-->
      <!--          <a href="#" class="nav-link active">首页</a>-->
      <!--          <a href="#" class="nav-link">模板</a>-->
      <!--          <a href="#" class="nav-link">创作指南</a>-->
      <!--          <a href="#" class="nav-link">社区</a>-->
      <!--        </nav>-->
      <!--      </div>-->
      <div class="navbar-right">
        <el-icon class="nav-icon"><Bell /></el-icon>
        <UserDropdown />
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 小说标题和返回按钮 -->
      <div class="novel-header">
        <div class="novel-title-section">
          <h1 class="novel-title">《{{ novelInfo.name || '星辰变' }}》</h1>
<!--          <p class="novel-author">作者：{{ novelInfo.author || '我吃西红柿' }}</p>-->
        </div>
        <div class="novel-actions">
          <a href="/dashboard" class="back-link">返回列表</a>
          <el-button type="primary" class="save-btn" @click="handleSave">
            <el-icon><Document /></el-icon>
            保存
          </el-button>
          <el-button class="share-btn" @click="handleShare">
            <el-icon><Share /></el-icon>
            分享
          </el-button>
        </div>
      </div>

      <!-- 标签页导航 -->
      <div class="tab-navigation">
        <div class="tab-list">
          <div
              v-for="tab in tabs"
              :key="tab.key"
              :class="['tab-item', { active: activeTab === tab.key }]"
              @click="activeTab = tab.key"
          >
            <el-icon class="tab-icon">
              <Monitor v-if="tab.key === 'overview'" />
              <User v-else-if="tab.key === 'characters'" />
              <List v-else-if="tab.key === 'toc'" />
              <Document v-else-if="tab.key === 'content'" />
              <Refresh v-else-if="tab.key === 'generation'" />
            </el-icon>
            {{ tab.label }}
          </div>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-area">
        <!-- 章节管理区域 -->
        <div class="chapter-management">
          <div class="chapter-actions">
            <el-button type="primary" class="add-chapter-btn" @click="handleAddChapter">
              <el-icon><Plus /></el-icon>
              + 添加章节
            </el-button>
            <!--            <el-button class="import-novel-btn" @click="handleImportNovel">-->
            <!--              <el-icon><Document /></el-icon>-->
            <!--              导入小说-->
            <!--            </el-button>-->
          </div>

          <div class="chapter-list">
            <h3>章节目录</h3>
            <div class="chapter-items">
              <div
                  v-for="chapter in chapters"
                  :key="chapter.id"
                  :class="['chapter-item', { active: selectedChapter?.id === chapter.id }]"
                  @click="selectChapter(chapter)"
              >
                <div class="chapter-drag-handle">
                  <el-icon><Rank /></el-icon>
                </div>
                <div class="chapter-info">
                  <span class="chapter-title">{{ chapter.novelChapter || chapter.title }}</span>
                </div>
                <div class="chapter-actions">
                  <el-icon class="more-icon"><MoreFilled /></el-icon>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 主内容区域 -->
        <div class="main-content-area">
          <!-- 概览标签页 -->
          <div v-if="activeTab === 'overview'" class="overview-tab">
            <!-- 基本信息 -->
            <div class="info-section">
              <h3>基本信息</h3>
              <div class="info-grid">
                <div class="info-item">
                  <label>小说名称</label>
                  <span>{{ novelInfo.name || '星辰变' }}</span>
                </div>
<!--                <div class="info-item">-->
<!--                  <label>作者</label>-->
<!--                  <span>{{ novelInfo.author || '我吃西红柿' }}</span>-->
<!--                </div>-->
                <div class="info-item">
                  <label>分类</label>
                  <span>{{ novelInfo.type || '玄幻/修真' }}</span>
                </div>
                <div class="info-item">
                  <label>状态</label>
                  <span>{{ novelInfo.status || '连载中' }}</span>
                </div>
                <div class="info-item">
                  <label>创建时间</label>
                  <span>{{ formatDate(novelInfo.createTime) || '2023-05-12' }}</span>
                </div>
                <div class="info-item">
                  <label>最后更新时间</label>
                  <span>{{ formatDate(novelInfo.updateTime) || '2023-10-28' }}</span>
                </div>
              </div>
            </div>

            <!-- 统计信息 -->
<!--            <div class="stats-section">-->
<!--              <h3>统计信息</h3>-->
<!--              <div class="stats-grid">-->
<!--                <div class="stat-card">-->
<!--                  <div class="stat-value">{{ novelStats.totalWords || '128,456' }}</div>-->
<!--                  <div class="stat-label">总字数</div>-->
<!--                </div>-->
<!--                <div class="stat-card">-->
<!--                  <div class="stat-value">{{ novelStats.chapterCount || '24' }}</div>-->
<!--                  <div class="stat-label">章节数</div>-->
<!--                </div>-->
<!--                <div class="stat-card">-->
<!--                  <div class="stat-value">{{ novelStats.characterCount || '18' }}</div>-->
<!--                  <div class="stat-label">人物数</div>-->
<!--                </div>-->
<!--                <div class="stat-card">-->
<!--                  <div class="stat-value">{{ novelStats.readCount || '1,245,789' }}</div>-->
<!--                  <div class="stat-label">阅读量</div>-->
<!--                </div>-->
<!--              </div>-->
<!--            </div>-->
          </div>

          <!-- 人物标签页 -->
          <div v-if="activeTab === 'characters'" class="characters-tab">
            <div class="tab-header">
              <h3>人物角色</h3>
              <el-button type="primary" @click="handleAddRole">
                <el-icon><Plus /></el-icon>
                添加人物
              </el-button>
            </div>

            <div class="characters-grid">
              <div
                  v-for="role in roles"
                  :key="role.id"
                  class="character-card"
              >
                <div class="character-avatar">
                  <img v-if="role.roleImg" :src="getImageUrl(role.roleImg)" :alt="role.roleName" />
                  <div v-else class="default-avatar">
                    {{ role.roleName?.charAt(0) || '?' }}
                  </div>
                </div>
                <div class="character-info">
                  <h4>{{ role.roleName }}</h4>
                  <p class="character-desc">{{ role.roleDetail || '暂无描述' }}</p>
                </div>
                <div class="character-actions">
                  <el-button size="small" type="primary" @click="editRole(role)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteRole(role)">删除</el-button>
                </div>
              </div>
            </div>

            <div v-if="roles.length === 0" class="empty-state">
              <el-icon><User /></el-icon>
              <p>暂无人物角色，点击上方按钮添加</p>
            </div>
          </div>


          <!-- 目录标签页 -->
          <div v-if="activeTab === 'toc'" class="toc-tab">
            <h3>章节目录</h3>
            <div class="chapter-table">
              <div class="table-header">
                <div class="col-title">章节标题</div>
                <div class="col-words">字数</div>
                <div class="col-status">状态</div>
                <div class="col-actions">操作</div>
              </div>
              <div
                  v-for="chapter in chapters"
                  :key="chapter.id"
                  class="table-row"
              >
                <div class="col-title">{{ chapter.novelChapter || chapter.title }}</div>
                <div class="col-words">{{ chapter.wordCount || '0' }}</div>
                <div class="col-status">
                  <el-tag type="success" class="status-tag">已完成</el-tag>
                </div>
                <div class="col-actions">
                  <el-button size="small" class="edit-btn" @click="editChapter(chapter)">编辑</el-button>
                  <el-button size="small" type="danger" class="delete-btn" @click="deleteChapter(chapter)">删除</el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 内容标签页 -->
          <div v-if="activeTab === 'content'" class="content-tab">
            <div v-if="selectedChapter" class="chapter-content">
              <h3>{{ selectedChapter.novelChapter || selectedChapter.title }}</h3>
              <div class="content-preview">
                <!-- vue-office 预览组件 -->
                <VueOfficeDocx
                    v-if="selectedChapter.filePath"
                    :src="getFileUrl(selectedChapter.filePath)"
                    style="height: 600px;"
                    @rendered="onDocumentRendered"
                    @error="onDocumentError"
                />
                <div v-else class="no-content">
                  <el-icon><Document /></el-icon>
                  <p>暂无内容，请上传文档</p>
                </div>
              </div>
            </div>
            <div v-else class="no-chapter-selected">
              <el-icon><Document /></el-icon>
              <p>请选择一个章节查看内容</p>
            </div>
          </div>

          <!-- 预览标签页 -->
          <div v-if="activeTab === 'preview'" class="preview-tab">
            <div class="preview-header">
              <h3>分镜预览</h3>
              <div class="preview-header-right">
                <span v-if="selectedChapter">
                  章节：{{ selectedChapter.novelChapter || selectedChapter.title }}
                </span>
                <el-button
                    type="primary"
                    @click="exportStoryboards"
                    :disabled="savedStoryboards.length === 0 || exporting"
                    :loading="exporting"
                    size="small"
                >
                  <el-icon><Download /></el-icon>
                  {{ exporting ? '导出中...' : '导出所有分镜' }}
                </el-button>
              </div>
            </div>

            <div class="preview-content">
              <div v-if="!selectedChapter" class="no-chapter-selected">
                <el-icon><Picture /></el-icon>
                <p>请选择一个章节查看分镜预览</p>
              </div>

              <div v-else-if="savedStoryboards.length === 0" class="no-storyboards">
                <el-icon><Picture /></el-icon>
                <p>该章节暂无分镜数据</p>
                <p class="hint">请在"生成记录"中生成分镜并保存</p>
              </div>

              <div v-else class="storyboard-preview-list">
                <div
                    v-for="(storyboard, index) in savedStoryboards"
                    :key="storyboard.id || index"
                    class="preview-item"
                >
                  <div class="preview-item-header">
                    <h4>分镜 {{ storyboard.name || storyboard.id }}</h4>
                  </div>
                  <div class="preview-item-image">
                    <img
                        v-if="storyboard.res_img"
                        :src="getImageUrl(storyboard.res_img)"
                        :alt="storyboard.name"
                        @error="handleImageError"
                    />
                    <div v-else class="no-image-preview">
                      <el-icon><Picture /></el-icon>
                      <p>暂无图片</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 生成记录标签页 -->
          <div v-if="activeTab === 'generation'" class="generation-tab">
            <div class="generation-header">
              <h3>分镜生成</h3>
              <el-button type="primary" @click="handleExtractChapterText" :loading="extracting">
                <el-icon><DocumentCopy /></el-icon>
                提取章节文字
              </el-button>
            </div>

            <div class="generation-content">
              <el-form :model="generationForm" label-width="120px">
                <el-form-item label="章节内容">
                  <el-input
                      v-model="generationForm.content"
                      type="textarea"
                      :rows="10"
                      placeholder="请先选择章节后点击'提取章节文字'按钮"
                  />
                </el-form-item>

                <el-form-item label="选择模型">
                  <el-select v-model="generationForm.text_model_id" placeholder="请选择文本模型" filterable style="width: 100%">
                    <el-option v-for="item in textModelOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>

                <el-form-item label="提示词模板">
                  <el-select v-model="generationForm.prompt_id" placeholder="请选择提示词模板" filterable style="width: 100%">
                    <el-option v-for="item in promptOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>

                <el-form-item label="图片模型">
                  <el-select v-model="generationForm.img_model_id" placeholder="请选择图片模型" filterable style="width: 100%">
                    <el-option v-for="item in imgModelOptions" :key="item.id" :label="item.model" :value="item.id" />
                  </el-select>
                </el-form-item>

                <el-form-item label="分镜提示词">
                  <div class="prompt-container">
                    <el-input
                        v-model="generationForm.storyPrompt"
                        type="textarea"
                        :rows="5"
                        placeholder="请输入分镜提示词，描述分镜的要求和格式"
                        class="prompt-textarea"
                    />
                    <div class="prompt-buttons">
                      <el-button
                          type="primary"
                          size="small"
                          :loading="optimizingStoryPrompt"
                          :disabled="optimizingStoryPrompt || generatingStoryboard || !generationForm.content"
                          @click="handleOptimizeStoryPrompt"
                      >
                        {{ optimizingStoryPrompt ? 'AI优化中...' : 'AI优化' }}
                      </el-button>
                    </div>
                  </div>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="handleGenerateStoryboard" :loading="generatingStoryboard" :disabled="!generationForm.content || !generationForm.storyPrompt">
                    <el-icon><VideoCamera /></el-icon>
                    生成分镜
                  </el-button>
                  <el-button @click="clearGenerationForm">清空</el-button>
                </el-form-item>

                <!-- 分镜列表展示 -->
                <el-form-item v-if="parsedStoryboards.length > 0" label="分镜列表">
                  <!-- 批量操作按钮 -->
                  <div class="batch-actions" style="margin-bottom: 16px;">
                    <el-button
                        type="warning"
                        @click="optimizeAllScenePrompts"
                        :loading="optimizingAllPrompts"
                        :disabled="optimizingAllPrompts || savingStoryboards || batchGeneratingImages"
                    >
                      <el-icon><MagicStick /></el-icon>
                      批量优化提示词
                    </el-button>
                    <el-button
                        type="primary"
                        @click="batchGenerateImages"
                        :loading="batchGeneratingImages"
                        :disabled="batchGeneratingImages || savingStoryboards || optimizingAllPrompts"
                    >
                      <el-icon><VideoCamera /></el-icon>
                      批量生成图片
                    </el-button>
                    <el-button
                        type="success"
                        @click="saveAllStoryboards"
                        :loading="savingStoryboards"
                        :disabled="savingStoryboards || optimizingAllPrompts || batchGeneratingImages"
                    >
                      <el-icon><Check /></el-icon>
                      保存所有分镜
                    </el-button>
                  </div>

                  <div class="storyboard-list">
                    <div
                        v-for="storyboard in parsedStoryboards"
                        :key="storyboard.id"
                        class="storyboard-item"
                    >
                      <div class="storyboard-header">
                        <h4>分镜 #{{ storyboard.id }}</h4>
                        <div class="storyboard-actions">
                          <el-button size="small" @click="editStoryboard(storyboard)">编辑</el-button>
                        </div>
                      </div>

                      <div class="storyboard-content">
                        <div class="storyboard-image">
                          <img v-if="storyboard.image" :src="getImageUrl(storyboard.image)" alt="分镜图片" />
                          <div v-else class="no-image">
                            <el-icon><Picture /></el-icon>
                            <p>暂无图片</p>
                          </div>
                          <div class="image-actions">
                            <el-button size="small" type="primary" @click="generateSceneImage(storyboard)" :loading="storyboard.generating">
                              生成图片
                            </el-button>
                          </div>
                        </div>

                        <!-- 参考图片显示 -->
                        <div v-if="storyboard.referenceImage" class="reference-image">
                          <h5>参考图片</h5>
                          <img :src="getImageUrl(storyboard.referenceImage)" alt="参考图片" />
                        </div>

                        <div class="storyboard-info">
                          <div class="info-row">
                            <label>画格大小：</label>
                            <el-input v-model="storyboard.size" size="small" />
                          </div>
                          <div class="info-row">
                            <label>位置构图：</label>
                            <el-input v-model="storyboard.position" size="small" />
                          </div>
                          <div class="info-row">
                            <label>表情神态：</label>
                            <el-input v-model="storyboard.expression" size="small" />
                          </div>
                          <div class="info-row">
                            <label>对话台词：</label>
                            <el-input v-model="storyboard.dialogue" type="textarea" :rows="2" size="small" />
                          </div>
                          <div class="info-row">
                            <label>场景描述：</label>
                            <el-input v-model="storyboard.description" type="textarea" :rows="3" size="small" />
                          </div>
                          <div class="info-row">
                            <label>出场人物：</label>
                            <el-input v-model="storyboard.characters_in_scene" size="small" placeholder="多个用逗号分隔" @blur="matchCharacters(storyboard)" />
                          </div>
                          <div class="info-row">
                            <label>图片提示词：</label>
                            <div class="prompt-input-group">
                              <el-input
                                  v-model="storyboard.imagePrompt"
                                  type="textarea"
                                  :rows="3"
                                  size="small"
                                  placeholder="AI将为分镜生成图片提示词，或手动输入..."
                              />
                              <el-button
                                  size="small"
                                  type="warning"
                                  @click="optimizeScenePrompt(storyboard)"
                                  :loading="storyboard.optimizing"
                                  style="margin-top: 8px;"
                              >
                                <el-icon><MagicStick /></el-icon>
                                优化提示词
                              </el-button>
                            </div>
                          </div>

                          <div v-if="storyboard.characters_in_scene" class="matched-characters">
                            <label>人物信息：</label>
                            <div class="character-cards">
                              <div
                                  v-for="(char, index) in storyboard.characters_list"
                                  :key="index"
                                  class="character-card"
                              >
                                <div class="character-avatar">
                                  <img v-if="char.image" :src="getImageUrl(char.image)" :alt="char.name" />
                                  <div v-else class="default-avatar">{{ char.name?.charAt(0) || '?' }}</div>
                                </div>
                                <div class="character-name">{{ char.name }}</div>
                                <div class="character-actions">
                                  <el-button
                                      v-if="!char.matched"
                                      size="small"
                                      type="success"
                                      @click="createNewCharacter(char.name, storyboard, index)"
                                  >
                                    创建角色
                                  </el-button>
                                  <el-button
                                      v-else-if="!char.image"
                                      size="small"
                                      type="warning"
                                      @click="uploadCharacterImage(char, storyboard, index)"
                                  >
                                    上传图片
                                  </el-button>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-form-item>

                <!-- 原始JSON结果展示 -->
                <el-form-item v-if="generationResult" label="原始JSON">
                  <el-input
                      v-model="generationResult"
                      type="textarea"
                      :rows="10"
                      readonly
                  />
                  <div class="result-actions">
                    <el-button type="success" size="small" @click="copyResult">复制结果</el-button>
                    <el-button size="small" @click="clearResult">清空结果</el-button>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加章节弹窗 -->
    <el-dialog
        v-model="showAddChapterDialog"
        title="添加章节"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="chapterForm" :rules="chapterRules" ref="chapterFormRef" label-width="100px">
        <el-form-item label="章节名称" prop="novelChapter" required>
          <el-input v-model="chapterForm.novelChapter" placeholder="请输入章节名称" />
        </el-form-item>

        <el-form-item label="上传文档" prop="filePath">
          <FileUpload
              v-model="chapterForm.filePath"
              :action="'/common/upload'"
              :file-type="['docx']"
              :file-size="10"
              :limit="1"
              :is-show-tip="true"
          />
        </el-form-item>

        <el-form-item label="涉及人物">
          <el-input
              v-model="chapterForm.refRole"
              placeholder="请输入涉及的人物，多个用逗号分隔"
              type="textarea"
              :rows="2"
          />
          <div class="form-tip">例如：张三,李四,王五</div>
        </el-form-item>

        <el-form-item label="章节概述">
          <el-input
              v-model="chapterForm.interpretation"
              placeholder="请输入章节概述或简介"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelChapter">取消</el-button>
          <el-button type="primary" @click="submitChapter" :loading="submitting">
            <el-icon><Check /></el-icon>
            确定添加
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑章节弹窗 -->
    <el-dialog
        v-model="showEditChapterDialog"
        title="编辑章节"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="editChapterForm" :rules="chapterRules" ref="editChapterFormRef" label-width="100px">
        <el-form-item label="章节名称" prop="novelChapter" required>
          <el-input v-model="editChapterForm.novelChapter" placeholder="请输入章节名称" />
        </el-form-item>

        <el-form-item label="上传文档" prop="filePath">
          <FileUpload
              v-model="editChapterForm.filePath"
              :action="'/common/upload'"
              :file-type="['docx']"
              :file-size="10"
              :limit="1"
              :is-show-tip="true"
          />
        </el-form-item>

        <el-form-item label="涉及人物">
          <el-input
              v-model="editChapterForm.refRole"
              placeholder="请输入涉及的人物，多个用逗号分隔"
              type="textarea"
              :rows="2"
          />
          <div class="form-tip">例如：张三,李四,王五</div>
        </el-form-item>

        <el-form-item label="章节概述">
          <el-input
              v-model="editChapterForm.interpretation"
              placeholder="请输入章节概述或简介"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelEditChapter">取消</el-button>
          <el-button type="primary" @click="submitEditChapter" :loading="editing">
            <el-icon><Check /></el-icon>
            确定修改
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入小说弹窗 -->
    <el-dialog
        v-model="showImportDialog"
        title="导入小说"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form :model="importForm" label-width="80px">
        <el-form-item label="上传文档">
          <el-upload
              ref="importUploadRef"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-success="handleImportSuccess"
              :on-error="handleImportError"
              :before-upload="beforeImportUpload"
              :file-list="importFileList"
              accept=".docx"
              :limit="1"
              :auto-upload="false"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 .docx 文件，支持批量导入章节
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showImportDialog = false">取消</el-button>
        <el-button type="primary" @click="submitImport" :loading="importing">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加人物弹窗 -->
    <el-dialog
        v-model="showAddRoleDialog"
        title="添加人物"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="roleForm" :rules="roleRules" ref="roleFormRef" label-width="120px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色描述" prop="roleDetail">
          <el-input
              v-model="roleForm.roleDetail"
              placeholder="请输入角色描述"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="角色衣着">
          <el-input
              v-model="roleForm.roleDress"
              placeholder="请输入角色衣着描述"
              type="textarea"
              :rows="2"
          />
        </el-form-item>

        <el-form-item label="文本模型" prop="text_model_id">
          <el-select v-model="roleForm.text_model_id" placeholder="请选择文本模型" filterable style="width: 100%">
            <el-option v-for="item in textModelOptions" :key="item.id" :label="item.model" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="图片模型" prop="img_model_id">
          <el-select v-model="roleForm.img_model_id" placeholder="请选择图片模型" filterable style="width: 100%">
            <el-option v-for="item in imgModelOptions" :key="item.id" :label="item.model" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="提示词模板" prop="prompt_id">
          <el-select v-model="roleForm.prompt_id" placeholder="请选择提示词模板" filterable style="width: 100%">
            <el-option v-for="item in promptOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="角色绘画提示词">
          <div class="prompt-container">
            <el-input
                v-model="roleForm.rolePromt"
                placeholder="请输入AI绘画提示词"
                type="textarea"
                :rows="3"
                maxlength="500"
                show-word-limit
                class="prompt-textarea"
            />
            <div class="prompt-buttons">
              <el-button
                  type="primary"
                  size="small"
                  :loading="roleOptimizing"
                  :disabled="roleOptimizing || roleGenerating || roleOptimizingAndGenerating"
                  @click="handleOptimizeRolePrompt"
              >
                {{ roleOptimizing ? 'AI优化中...' : 'AI优化' }}
              </el-button>
              <el-button
                  type="success"
                  size="small"
                  :loading="roleGenerating"
                  :disabled="roleOptimizing || roleGenerating || roleOptimizingAndGenerating || !roleForm.rolePromt"
                  @click="handleGenerateRoleImage"
              >
                {{ roleGenerating ? '生成中...' : (roleForm.refImg ? '生成图片(参考)' : '生成图片') }}
              </el-button>
              <el-button
                  type="warning"
                  size="small"
                  :loading="roleOptimizingAndGenerating"
                  :disabled="roleOptimizingAndGenerating || !roleForm.roleName || !roleForm.text_model_id || !roleForm.img_model_id || !roleForm.prompt_id"
                  @click="handleOptimizeAndGenerateRole"
              >
                {{ roleOptimizingAndGenerating ? '优化并生成中...' : '优化并生成' }}
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="角色图片">
          <ImageUpload
              v-model="roleForm.roleImg"
              :action="'/common/upload'"
              :file-type="['png', 'jpg', 'jpeg']"
              :file-size="5"
              :limit="1"
              :is-show-tip="true"
          />
        </el-form-item>

        <el-form-item label="参考图片">
          <ImageUpload
              v-model="roleForm.refImg"
              :action="'/common/upload'"
              :file-type="['png', 'jpg', 'jpeg']"
              :file-size="5"
              :limit="5"
              :is-show-tip="true"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelRole">取消</el-button>
          <el-button type="primary" @click="submitRole" :loading="roleSubmitting">
            <el-icon><Check /></el-icon>
            确定添加
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑人物弹窗 -->
    <el-dialog
        v-model="showEditRoleDialog"
        title="编辑人物"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="editRoleForm" :rules="roleRules" ref="editRoleFormRef" label-width="120px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色描述" prop="roleDetail">
          <el-input
              v-model="editRoleForm.roleDetail"
              placeholder="请输入角色描述"
              type="textarea"
              :rows="3"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>

        <el-form-item label="角色衣着">
          <el-input
              v-model="editRoleForm.roleDress"
              placeholder="请输入角色衣着描述"
              type="textarea"
              :rows="2"
          />
        </el-form-item>

        <el-form-item label="文本模型" prop="text_model_id">
          <el-select v-model="editRoleForm.text_model_id" placeholder="请选择文本模型" filterable style="width: 100%">
            <el-option v-for="item in textModelOptions" :key="item.id" :label="item.model" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="图片模型" prop="img_model_id">
          <el-select v-model="editRoleForm.img_model_id" placeholder="请选择图片模型" filterable style="width: 100%">
            <el-option v-for="item in imgModelOptions" :key="item.id" :label="item.model" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="提示词模板" prop="prompt_id">
          <el-select v-model="editRoleForm.prompt_id" placeholder="请选择提示词模板" filterable style="width: 100%">
            <el-option v-for="item in promptOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="角色绘画提示词">
          <div class="prompt-container">
            <el-input
                v-model="editRoleForm.rolePromt"
                placeholder="请输入AI绘画提示词"
                type="textarea"
                :rows="3"
                maxlength="500"
                show-word-limit
                class="prompt-textarea"
            />
            <div class="prompt-buttons">
              <el-button
                  type="primary"
                  size="small"
                  :loading="roleOptimizing"
                  :disabled="roleOptimizing || roleGenerating || roleOptimizingAndGenerating"
                  @click="handleOptimizeRolePromptForEdit"
              >
                {{ roleOptimizing ? 'AI优化中...' : 'AI优化' }}
              </el-button>
              <el-button
                  type="success"
                  size="small"
                  :loading="roleGenerating"
                  :disabled="roleOptimizing || roleGenerating || roleOptimizingAndGenerating || !editRoleForm.rolePromt"
                  @click="handleGenerateRoleImageForEdit"
              >
                {{ roleGenerating ? '生成中...' : (editRoleForm.refImg ? '生成图片(参考)' : '生成图片') }}
              </el-button>
              <el-button
                  type="warning"
                  size="small"
                  :loading="roleOptimizingAndGenerating"
                  :disabled="roleOptimizingAndGenerating || !editRoleForm.roleName || !editRoleForm.text_model_id || !editRoleForm.img_model_id || !editRoleForm.prompt_id"
                  @click="handleOptimizeAndGenerateRoleForEdit"
              >
                {{ roleOptimizingAndGenerating ? '优化并生成中...' : '优化并生成' }}
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="角色图片">
          <ImageUpload
              v-model="editRoleForm.roleImg"
              :action="'/common/upload'"
              :file-type="['png', 'jpg', 'jpeg']"
              :file-size="5"
              :limit="1"
              :is-show-tip="true"
          />
        </el-form-item>

        <el-form-item label="参考图片">
          <ImageUpload
              v-model="editRoleForm.refImg"
              :action="'/common/upload'"
              :file-type="['png', 'jpg', 'jpeg']"
              :file-size="5"
              :limit="5"
              :is-show-tip="true"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelEditRole">取消</el-button>
          <el-button type="primary" @click="submitEditRole" :loading="roleEditing">
            <el-icon><Check /></el-icon>
            确定修改
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Bell,
  Document,
  Share,
  Plus,
  Rank,
  MoreFilled,
  Check,
  ArrowLeft,
  Monitor,
  User,
  List,
  Refresh,
  DocumentCopy,
  VideoCamera,
  Picture,
  MagicStick,
  View,
  Download
} from '@element-plus/icons-vue'
import UserDropdown from '@/views/dashboard/components/UserDropdown.vue'
import FileUpload from '@/components/FileUpload/index.vue'
import ImageUpload from '@/components/ImageUpload/index.vue'
import { getNovel } from '@/api/novel/novel'
import { listChapter, addChapter, updateChapter, delChapter } from '@/api/novel/chapter'
import { listRole, addRole, updateRole, delRole, optimizeRolePrompt, generateRoleImage, generateRoleImageWithReference } from '@/api/novel/role'
import { generateStoryboard, extractDocxText, optimizeStoryPrompt, optimizeStoryImgPrompt, addStoryboard, listStoryboardByNovelAndChapter } from '@/api/novel/storyboard'
import { listConfig as listModelConfig } from '@/api/model/config'
import { listConfig as listPromptConfig } from '@/api/prompt/config'
import VueOfficeDocx from '@vue-office/docx'
import '@vue-office/docx/lib/index.css'

const route = useRoute()
const router = useRouter()

// 响应式数据
const novelId = ref(route.params.id)
const activeTab = ref('overview')
const selectedChapter = ref(null)
const showAddChapterDialog = ref(false)
const showEditChapterDialog = ref(false)
const showImportDialog = ref(false)
const submitting = ref(false)
const editing = ref(false)
const importing = ref(false)

// 角色管理相关
const roles = ref([])
const showAddRoleDialog = ref(false)
const showEditRoleDialog = ref(false)
const roleSubmitting = ref(false)
const roleEditing = ref(false)
const roleOptimizing = ref(false)
const roleGenerating = ref(false)
const roleOptimizingAndGenerating = ref(false)

// 模型和提示词选项
const textModelOptions = ref([])
const imgModelOptions = ref([])
const promptOptions = ref([])

// 分镜生成相关
const extracting = ref(false)
const generatingStoryboard = ref(false)
const optimizingStoryPrompt = ref(false)
const optimizingAllPrompts = ref(false)
const savingStoryboards = ref(false)
const batchGeneratingImages = ref(false)
const generationResult = ref('')
const storyboardPrompt = ref('')
const parsedStoryboards = ref([])
const savedStoryboards = ref([]) // 保存的分镜数据（用于预览）
const exporting = ref(false) // 导出状态
const generationForm = reactive({
  content: '',
  text_model_id: null,
  prompt_id: null,
  img_model_id: null,
  storyPrompt: ''
})

// 标签页配置
const tabs = [
  { key: 'overview', label: '概览', icon: 'Monitor' },
  { key: 'characters', label: '人物', icon: 'User' },
  { key: 'toc', label: '目录', icon: 'List' },
  { key: 'content', label: '内容', icon: 'Document' },
  { key: 'preview', label: '预览', icon: 'View' },
  { key: 'generation', label: '生成记录', icon: 'Refresh' }
]

// 小说信息
const novelInfo = ref({})
const novelStats = ref({})
const chapters = ref([])

// 角色表单
const roleForm = reactive({
  novelId: novelId.value,
  roleName: '',
  roleDetail: '',
  roleDress: '',
  rolePromt: '',
  roleImg: '',
  refImg: '',
  text_model_id: null,
  img_model_id: null,
  prompt_id: null
})

// 编辑角色表单
const editRoleForm = reactive({
  id: null,
  novelId: novelId.value,
  roleName: '',
  roleDetail: '',
  roleDress: '',
  rolePromt: '',
  roleImg: '',
  refImg: '',
  text_model_id: null,
  img_model_id: null,
  prompt_id: null
})

// 角色表单验证规则
const roleRules = reactive({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 1, max: 50, message: '角色名称长度在 1 到 50 个字符', trigger: 'blur' }
  ]
})

// 表单引用
const roleFormRef = ref()
const editRoleFormRef = ref()


// 章节表单
const chapterForm = reactive({
  novelChapter: '',      // 章节名称
  novelId: novelId.value, // 小说ID
  filePath: '',          // 文件路径
  refRole: '',           // 涉及人物
  interpretation: ''     // 概述
})

// 编辑章节表单
const editChapterForm = reactive({
  id: null,              // 章节ID
  novelChapter: '',      // 章节名称
  novelId: novelId.value, // 小说ID
  filePath: '',          // 文件路径
  refRole: '',           // 涉及人物
  interpretation: ''     // 概述
})

// 章节表单验证规则
const chapterRules = reactive({
  novelChapter: [
    { required: true, message: '请输入章节名称', trigger: 'blur' },
    { min: 1, max: 100, message: '章节名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  filePath: [
    { required: true, message: '请上传章节文档', trigger: 'change' }
  ]
})

// 表单引用
const chapterFormRef = ref()
const editChapterFormRef = ref()

// 导入表单
const importForm = reactive({
  novelId: novelId.value
})

// 文件上传
const importUploadRef = ref()
const importFileList = ref([])

// 获取文件URL（添加/dev-api前缀）
const getFileUrl = (filePath) => {
  if (!filePath) return ''
  if (filePath.startsWith('http')) return filePath
  return `/dev-api${filePath}`
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  if (imagePath.startsWith('http')) return imagePath
  return `/dev-api${imagePath}`
}

// 加载小说信息
const loadNovelInfo = async () => {
  try {
    const response = await getNovel(novelId.value)
    if (response.code === 200) {
      novelInfo.value = response.data
    }
  } catch (error) {
    console.error('Load novel info error:', error)
    ElMessage.error('获取小说信息失败')
  }
}

// 加载章节列表
const loadChapters = async () => {
  try {
    const response = await listChapter({ novelId: novelId.value })
    if (response.code === 200) {
      chapters.value = response.rows || []
    }
  } catch (error) {
    console.error('Load chapters error:', error)
    ElMessage.error('获取章节列表失败')
  }
}

// 加载角色列表
const loadRoles = async () => {
  try {
    const response = await listRole({ novelId: novelId.value })
    if (response.code === 200) {
      roles.value = response.rows || []
    }
  } catch (error) {
    console.error('Load roles error:', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 选择章节
const selectChapter = async (chapter) => {
  selectedChapter.value = chapter
  if (activeTab.value !== 'content') {
    activeTab.value = 'content'
  }

  // 加载该章节的持久化分镜数据
  await loadChapterStoryboards(chapter.id)
}

// 加载章节分镜数据
const loadChapterStoryboards = async (chapterId) => {
  if (!chapterId || !novelId.value) {
    return
  }

  try {
    const response = await listStoryboardByNovelAndChapter(novelId.value, chapterId)

    if (response.code === 200 && response.data && response.data.length > 0) {
      // 同时保存原始数据用于预览
      savedStoryboards.value = response.data

      // 解析JSON数据还原分镜列表
      parsedStoryboards.value = response.data.map(item => {
        // 解析prompt_json
        let sceneData = {}
        if (item.promptJson) {
          try {
            sceneData = typeof item.promptJson === 'string' ? JSON.parse(item.promptJson) : item.promptJson
            console.log('解析分镜JSON数据:', sceneData)
          } catch (e) {
            console.error('Parse promptJson error:', e)
          }
        }

        // 构建分镜对象 - 确保所有字段都从JSON中正确解析
        const storyboard = {
          id: item.name ? parseInt(item.name.replace('分镜 ', '')) : Date.now(),
          size: sceneData.size || '',                         // 画格大小
          position: sceneData.position || '',                 // 位置构图
          expression: sceneData.expression || '',             // 表情神态
          dialogue: sceneData.dialogue || '',                 // 对话台词
          description: sceneData.description || '',           // 场景描述
          characters_in_scene: sceneData.characters_in_scene || item.refRole || '',  // 出场人物
          imagePrompt: item.prompt || '',                     // 图片提示词
          referenceImage: item.img || '',                     // 参考图片
          image: item.res_img || '',                          // 最终生成的分镜图片
          generating: false,
          optimizing: false,
          characters_list: []
        }

        return storyboard
      })

      // 为每个分镜匹配人物信息
      parsedStoryboards.value.forEach(storyboard => {
        if (storyboard.characters_in_scene) {
          matchCharacters(storyboard)
        }
      })

      ElMessage.success(`已加载 ${parsedStoryboards.value.length} 个分镜`)
    } else {
      // 没有数据，清空列表
      parsedStoryboards.value = []
      savedStoryboards.value = []
    }
  } catch (error) {
    console.error('Load chapter storyboards error:', error)
    // 加载失败时不显示错误，避免影响用户体验
    parsedStoryboards.value = []
    savedStoryboards.value = []
  }
}

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.style.display = 'none'
}

// 导出所有分镜为一张长图
const exportStoryboards = async () => {
  if (savedStoryboards.value.length === 0) {
    ElMessage.warning('没有可导出的分镜')
    return
  }

  try {
    exporting.value = true
    ElMessage.info('正在导出分镜图片...')

    // 创建canvas
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')

    // 设置canvas宽度（用于漫画）
    const canvasWidth = 800
    let totalHeight = 0

    // 预加载所有图片并计算总高度
    const images = []
    for (const storyboard of savedStoryboards.value) {
      if (storyboard.res_img) {
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.src = getImageUrl(storyboard.res_img)

        await new Promise((resolve, reject) => {
          img.onload = () => {
            const aspectRatio = img.height / img.width
            const imgHeight = canvasWidth * aspectRatio
            images.push({ img, height: imgHeight })
            totalHeight += imgHeight + 40 // 40px间距
            resolve()
          }
          img.onerror = reject
        })
      }
    }

    // 设置canvas高度
    canvas.width = canvasWidth
    canvas.height = totalHeight

    // 绘制所有图片
    let currentY = 0
    ctx.fillStyle = '#fafbfc'
    ctx.fillRect(0, 0, canvas.width, canvas.height)

    for (const item of images) {
      const { img, height } = item
      ctx.drawImage(img, 0, currentY, canvasWidth, height)
      currentY += height + 40
    }

    // 导出为PNG
    const fileName = `分镜预览-${selectedChapter.value?.novelChapter || selectedChapter.value?.title || '章节'}-${Date.now()}.png`
    canvas.toBlob((blob) => {
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = fileName
      a.click()
      URL.revokeObjectURL(url)

      ElMessage.success('分镜导出成功！')
      exporting.value = false
    }, 'image/png')

  } catch (error) {
    console.error('Export storyboards error:', error)
    ElMessage.error('导出失败，请重试')
    exporting.value = false
  }
}

// 添加章节
const handleAddChapter = () => {
  // 重置表单
  chapterForm.novelChapter = ''
  chapterForm.filePath = ''
  chapterForm.refRole = ''
  chapterForm.interpretation = ''

  // 清除表单验证
  if (chapterFormRef.value) {
    chapterFormRef.value.clearValidate()
  }

  showAddChapterDialog.value = true
}

// 导入小说
const handleImportNovel = () => {
  importFileList.value = []
  showImportDialog.value = true
}

// 导入文件上传前检查
const beforeImportUpload = (file) => {
  const isDocx = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isDocx) {
    ElMessage.error('只能上传 .docx 文件!')
    return false
  }

  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
    return false
  }

  return true
}

const handleImportSuccess = (response) => {
  if (response.code === 200) {
    importForm.filePath = response.data.url
    ElMessage.success('文件上传成功')
  } else {
    ElMessage.error(response.msg || '文件上传失败')
  }
}

const handleImportError = (error) => {
  console.error('Import upload error:', error)
  ElMessage.error('文件上传失败')
}

// 提交章节
const submitChapter = async () => {
  // 表单验证
  if (!chapterFormRef.value) return

  try {
    await chapterFormRef.value.validate()
  } catch (error) {
    ElMessage.error('请完善必填信息')
    return
  }

  try {
    submitting.value = true
    const response = await addChapter(chapterForm)
    if (response.code === 200) {
      ElMessage.success('章节添加成功')
      showAddChapterDialog.value = false
      loadChapters()
    } else {
      ElMessage.error(response.msg || '章节添加失败')
    }
  } catch (error) {
    console.error('Add chapter error:', error)
    ElMessage.error('章节添加失败')
  } finally {
    submitting.value = false
  }
}

// 取消添加章节
const handleCancelChapter = () => {
  showAddChapterDialog.value = false
  // 重置表单
  chapterForm.novelChapter = ''
  chapterForm.filePath = ''
  chapterForm.refRole = ''
  chapterForm.interpretation = ''

  // 清除表单验证
  if (chapterFormRef.value) {
    chapterFormRef.value.clearValidate()
  }
}

// 提交导入
const submitImport = async () => {
  if (!importForm.filePath) {
    ElMessage.error('请先上传文件')
    return
  }

  try {
    importing.value = true
    // 这里可以调用批量导入章节的API
    ElMessage.success('导入功能开发中...')
    showImportDialog.value = false
  } catch (error) {
    console.error('Import error:', error)
    ElMessage.error('导入失败')
  } finally {
    importing.value = false
  }
}

// 编辑章节
const editChapter = (chapter) => {
  // 填充编辑表单
  editChapterForm.id = chapter.id
  editChapterForm.novelChapter = chapter.novelChapter || chapter.title || ''
  editChapterForm.filePath = chapter.filePath || ''
  editChapterForm.refRole = chapter.refRole || ''
  editChapterForm.interpretation = chapter.interpretation || ''

  // 清除表单验证
  if (editChapterFormRef.value) {
    editChapterFormRef.value.clearValidate()
  }

  showEditChapterDialog.value = true
}

// 提交编辑章节
const submitEditChapter = async () => {
  // 表单验证
  if (!editChapterFormRef.value) return

  try {
    await editChapterFormRef.value.validate()
  } catch (error) {
    ElMessage.error('请完善必填信息')
    return
  }

  try {
    editing.value = true
    const response = await updateChapter(editChapterForm)
    if (response.code === 200) {
      ElMessage.success('章节修改成功')
      showEditChapterDialog.value = false
      loadChapters()
    } else {
      ElMessage.error(response.msg || '章节修改失败')
    }
  } catch (error) {
    console.error('Update chapter error:', error)
    ElMessage.error('章节修改失败')
  } finally {
    editing.value = false
  }
}

// 取消编辑章节
const handleCancelEditChapter = () => {
  showEditChapterDialog.value = false
  // 重置表单
  editChapterForm.id = null
  editChapterForm.novelChapter = ''
  editChapterForm.filePath = ''
  editChapterForm.refRole = ''
  editChapterForm.interpretation = ''

  // 清除表单验证
  if (editChapterFormRef.value) {
    editChapterFormRef.value.clearValidate()
  }
}

// 删除章节
const deleteChapter = async (chapter) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除章节"${chapter.novelChapter || chapter.title}"吗？删除后无法恢复！`,
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
    )

    const response = await delChapter(chapter.id)
    if (response.code === 200) {
      ElMessage.success('章节删除成功')
      // 如果删除的是当前选中的章节，清空选择
      if (selectedChapter.value && selectedChapter.value.id === chapter.id) {
        selectedChapter.value = null
      }
      loadChapters()
    } else {
      ElMessage.error(response.msg || '章节删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete chapter error:', error)
      ElMessage.error('章节删除失败')
    }
  }
}

// 角色管理相关方法

// 添加角色
const handleAddRole = () => {
  // 重置表单
  roleForm.novelId = novelId.value
  roleForm.roleName = ''
  roleForm.roleDetail = ''
  roleForm.roleDress = ''
  roleForm.rolePromt = ''
  roleForm.roleImg = ''
  roleForm.refImg = ''
  roleForm.text_model_id = null
  roleForm.img_model_id = null
  roleForm.prompt_id = null

  // 清除表单验证
  if (roleFormRef.value) {
    roleFormRef.value.clearValidate()
  }

  showAddRoleDialog.value = true
}

// 提交角色
const submitRole = async () => {
  // 表单验证
  if (!roleFormRef.value) return

  try {
    await roleFormRef.value.validate()
  } catch (error) {
    ElMessage.error('请完善必填信息')
    return
  }

  try {
    roleSubmitting.value = true
    const response = await addRole(roleForm)
    if (response.code === 200) {
      ElMessage.success('角色添加成功')
      showAddRoleDialog.value = false

      // 重新加载角色列表
      loadRoles().then(() => {
        // 更新所有分镜的人物匹配信息
        parsedStoryboards.value.forEach(storyboard => {
          if (storyboard.characters_in_scene) {
            matchCharacters(storyboard)
          }
        })

        // 清除创建角色的标记
        creatingCharacterStoryboard = null
      })
    } else {
      ElMessage.error(response.msg || '角色添加失败')
    }
  } catch (error) {
    console.error('Add role error:', error)
    ElMessage.error('角色添加失败')
  } finally {
    roleSubmitting.value = false
  }
}

// 取消添加角色
const handleCancelRole = () => {
  showAddRoleDialog.value = false
  // 重置表单
  roleForm.novelId = novelId.value
  roleForm.roleName = ''
  roleForm.roleDetail = ''
  roleForm.roleDress = ''
  roleForm.rolePromt = ''
  roleForm.roleImg = ''
  roleForm.refImg = ''
  roleForm.text_model_id = null
  roleForm.img_model_id = null
  roleForm.prompt_id = null

  // 清除表单验证
  if (roleFormRef.value) {
    roleFormRef.value.clearValidate()
  }
}

// 编辑角色
const editRole = (role) => {
  // 填充编辑表单
  editRoleForm.id = role.id
  editRoleForm.novelId = role.novelId
  editRoleForm.roleName = role.roleName || ''
  editRoleForm.roleDetail = role.roleDetail || ''
  editRoleForm.roleDress = role.roleDress || ''
  editRoleForm.rolePromt = role.rolePromt || ''
  editRoleForm.roleImg = role.roleImg || ''
  editRoleForm.refImg = role.refImg || ''

  // 清除表单验证
  if (editRoleFormRef.value) {
    editRoleFormRef.value.clearValidate()
  }

  showEditRoleDialog.value = true
}

// 提交编辑角色
const submitEditRole = async () => {
  // 表单验证
  if (!editRoleFormRef.value) return

  try {
    await editRoleFormRef.value.validate()
  } catch (error) {
    ElMessage.error('请完善必填信息')
    return
  }

  try {
    roleEditing.value = true
    const response = await updateRole(editRoleForm)
    if (response.code === 200) {
      ElMessage.success('角色修改成功')
      showEditRoleDialog.value = false

      // 重新加载角色列表并更新所有分镜的人物信息
      loadRoles().then(() => {
        parsedStoryboards.value.forEach(storyboard => {
          if (storyboard.characters_in_scene) {
            matchCharacters(storyboard)
          }
        })
      })
    } else {
      ElMessage.error(response.msg || '角色修改失败')
    }
  } catch (error) {
    console.error('Update role error:', error)
    ElMessage.error('角色修改失败')
  } finally {
    roleEditing.value = false
  }
}

// 取消编辑角色
const handleCancelEditRole = () => {
  showEditRoleDialog.value = false
  // 重置表单
  editRoleForm.id = null
  editRoleForm.novelId = novelId.value
  editRoleForm.roleName = ''
  editRoleForm.roleDetail = ''
  editRoleForm.roleDress = ''
  editRoleForm.rolePromt = ''
  editRoleForm.roleImg = ''
  editRoleForm.refImg = ''
  editRoleForm.text_model_id = null
  editRoleForm.img_model_id = null
  editRoleForm.prompt_id = null

  // 清除表单验证
  if (editRoleFormRef.value) {
    editRoleFormRef.value.clearValidate()
  }
}

// 删除角色
const deleteRole = async (role) => {
  try {
    await ElMessageBox.confirm(
        `确定要删除角色"${role.roleName}"吗？删除后无法恢复！`,
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
    )

    const response = await delRole(role.id)
    if (response.code === 200) {
      ElMessage.success('角色删除成功')

      // 重新加载角色列表并更新所有分镜的人物信息
      loadRoles().then(() => {
        parsedStoryboards.value.forEach(storyboard => {
          if (storyboard.characters_in_scene) {
            matchCharacters(storyboard)
          }
        })
      })
    } else {
      ElMessage.error(response.msg || '角色删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete role error:', error)
      ElMessage.error('角色删除失败')
    }
  }
}

// 保存
const handleSave = () => {
  ElMessage.success('保存成功')
}

// 分享
const handleShare = () => {
  ElMessage.info('分享功能开发中...')
}

// 返回首页
const goBackToDashboard = () => {
  router.push('/dashboard')
}


// 文档渲染完成
const onDocumentRendered = () => {
  console.log('Document rendered')
}

// 文档渲染错误
const onDocumentError = (error) => {
  console.error('Document render error:', error)
  ElMessage.error('文档预览失败')
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 加载模型和提示词选项
const loadModelAndPromptOptions = async () => {
  try {
    const [modelResponse, promptResponse] = await Promise.all([
      listModelConfig({ pageNum: 1, pageSize: 100 }),
      listPromptConfig({ pageNum: 1, pageSize: 100 })
    ])

    if (modelResponse.code === 200) {
      textModelOptions.value = modelResponse.rows || []
      imgModelOptions.value = modelResponse.rows || []
    }

    if (promptResponse.code === 200) {
      promptOptions.value = promptResponse.rows || []
    }
  } catch (error) {
    console.error('Load model and prompt options error:', error)
  }
}

// AI优化角色提示词
const handleOptimizeRolePrompt = async () => {
  if (!roleForm.roleName) {
    ElMessage.warning('请先填写角色名称')
    return
  }
  if (!roleForm.text_model_id) {
    ElMessage.warning('请先选择文本模型')
    return
  }
  if (!roleForm.prompt_id) {
    ElMessage.warning('请先选择提示词模板')
    return
  }

  try {
    roleOptimizing.value = true
    ElMessage.info('AI正在优化提示词，请耐心等待...')

    const requestData = {
      prompt_id: roleForm.prompt_id,
      text_model_id: roleForm.text_model_id,
      img_model_id: roleForm.img_model_id,
      role_name: roleForm.roleName,
      role_detail: roleForm.roleDetail,
      role_dress: roleForm.roleDress,
      role_prompt: roleForm.rolePromt,
      role_img: roleForm.roleImg,
      ref_img: roleForm.refImg
    }

    const response = await optimizeRolePrompt(requestData)
    if (response.success) {
      roleForm.rolePromt = response.optimizedPrompt
      ElMessage.success('AI优化成功！')
    } else {
      ElMessage.error('AI优化失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('AI optimize error:', error)
    ElMessage.error('AI优化失败：' + (error.message || '请重试'))
  } finally {
    roleOptimizing.value = false
  }
}

// 为编辑对话框优化提示词
const handleOptimizeRolePromptForEdit = async () => {
  if (!editRoleForm.roleName) {
    ElMessage.warning('请先填写角色名称')
    return
  }
  if (!editRoleForm.text_model_id) {
    ElMessage.warning('请先选择文本模型')
    return
  }
  if (!editRoleForm.prompt_id) {
    ElMessage.warning('请先选择提示词模板')
    return
  }

  try {
    roleOptimizing.value = true
    ElMessage.info('AI正在优化提示词，请耐心等待...')

    const requestData = {
      prompt_id: editRoleForm.prompt_id,
      text_model_id: editRoleForm.text_model_id,
      img_model_id: editRoleForm.img_model_id,
      role_name: editRoleForm.roleName,
      role_detail: editRoleForm.roleDetail,
      role_dress: editRoleForm.roleDress,
      role_prompt: editRoleForm.rolePromt,
      role_img: editRoleForm.roleImg,
      ref_img: editRoleForm.refImg
    }

    const response = await optimizeRolePrompt(requestData)
    if (response.success) {
      editRoleForm.rolePromt = response.optimizedPrompt
      ElMessage.success('AI优化成功！')
    } else {
      ElMessage.error('AI优化失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('AI optimize error:', error)
    ElMessage.error('AI优化失败：' + (error.message || '请重试'))
  } finally {
    roleOptimizing.value = false
  }
}

// 生成角色图片
const handleGenerateRoleImage = async () => {
  if (!roleForm.rolePromt) {
    ElMessage.warning('请先填写角色绘画提示词')
    return
  }
  if (!roleForm.img_model_id) {
    ElMessage.warning('请先选择图片模型')
    return
  }

  try {
    roleGenerating.value = true
    ElMessage.info('正在生成图片，请耐心等待...')

    let response
    if (roleForm.refImg) {
      // 解析 refImg，取第一个图片
      const refImages = roleForm.refImg.split(',').filter(img => img.trim())
      response = await generateRoleImageWithReference(
          roleForm.img_model_id,
          roleForm.rolePromt,
          refImages[0] || null,
          refImages[1] || null,
          refImages[2] || null
      )
    } else {
      response = await generateRoleImage(roleForm.img_model_id, roleForm.rolePromt)
    }

    if (response.success) {
      const imageUrl = response.localUrl || response.imageUrl
      if (imageUrl) {
        roleForm.roleImg = imageUrl
        ElMessage.success('图片生成成功！')
      } else {
        ElMessage.error('图片生成失败：未返回有效的图片URL')
      }
    } else {
      ElMessage.error('图片生成失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('Generate image error:', error)
    ElMessage.error('图片生成失败：' + (error.message || '请重试'))
  } finally {
    roleGenerating.value = false
  }
}

// 为编辑对话框生成图片
const handleGenerateRoleImageForEdit = async () => {
  if (!editRoleForm.rolePromt) {
    ElMessage.warning('请先填写角色绘画提示词')
    return
  }
  if (!editRoleForm.img_model_id) {
    ElMessage.warning('请先选择图片模型')
    return
  }

  try {
    roleGenerating.value = true
    ElMessage.info('正在生成图片，请耐心等待...')

    let response
    if (editRoleForm.refImg) {
      const refImages = editRoleForm.refImg.split(',').filter(img => img.trim())
      response = await generateRoleImageWithReference(
          editRoleForm.img_model_id,
          editRoleForm.rolePromt,
          refImages[0] || null,
          refImages[1] || null,
          refImages[2] || null
      )
    } else {
      response = await generateRoleImage(editRoleForm.img_model_id, editRoleForm.rolePromt)
    }

    if (response.success) {
      const imageUrl = response.localUrl || response.imageUrl
      if (imageUrl) {
        editRoleForm.roleImg = imageUrl
        ElMessage.success('图片生成成功！')
      } else {
        ElMessage.error('图片生成失败：未返回有效的图片URL')
      }
    } else {
      ElMessage.error('图片生成失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('Generate image error:', error)
    ElMessage.error('图片生成失败：' + (error.message || '请重试'))
  } finally {
    roleGenerating.value = false
  }
}

// 优化并生成角色图片
const handleOptimizeAndGenerateRole = async () => {
  if (!roleForm.roleName) {
    ElMessage.warning('请先填写角色名称')
    return
  }
  if (!roleForm.text_model_id) {
    ElMessage.warning('请先选择文本模型')
    return
  }
  if (!roleForm.img_model_id) {
    ElMessage.warning('请先选择图片模型')
    return
  }
  if (!roleForm.prompt_id) {
    ElMessage.warning('请先选择提示词模板')
    return
  }

  try {
    roleOptimizingAndGenerating.value = true
    ElMessage.info('正在同时优化提示词和生成图片，请耐心等待...')

    const requestData = {
      prompt_id: roleForm.prompt_id,
      text_model_id: roleForm.text_model_id,
      img_model_id: roleForm.img_model_id,
      role_name: roleForm.roleName,
      role_detail: roleForm.roleDetail,
      role_dress: roleForm.roleDress,
      role_prompt: roleForm.rolePromt,
      role_img: roleForm.roleImg,
      ref_img: roleForm.refImg
    }

    // 同时调用优化提示词和生成图片接口
    const [optimizeResponse, generateResponse] = await Promise.allSettled([
      optimizeRolePrompt(requestData),
      roleForm.refImg
        ? generateRoleImageWithReference(
            roleForm.img_model_id,
            roleForm.rolePromt,
            roleForm.refImg.split(',')[0] || null,
            roleForm.refImg.split(',')[1] || null,
            roleForm.refImg.split(',')[2] || null
          )
        : generateRoleImage(roleForm.img_model_id, roleForm.rolePromt)
    ])

    // 处理优化提示词的结果
    if (optimizeResponse.status === 'fulfilled' && optimizeResponse.value.success) {
      roleForm.rolePromt = optimizeResponse.value.optimizedPrompt
      ElMessage.success('AI优化成功！')
    } else if (optimizeResponse.status === 'rejected') {
      console.error('AI optimize error:', optimizeResponse.reason)
      ElMessage.warning('AI优化失败，但图片生成继续进行')
    }

    // 处理生成图片的结果
    if (generateResponse.status === 'fulfilled' && generateResponse.value.success) {
      const imageUrl = generateResponse.value.localUrl || generateResponse.value.imageUrl
      if (imageUrl) {
        roleForm.roleImg = imageUrl
        ElMessage.success('图片生成成功！')
      } else {
        ElMessage.error('图片生成失败：未返回有效的图片URL')
      }
    } else if (generateResponse.status === 'rejected') {
      console.error('Generate image error:', generateResponse.reason)
      ElMessage.error('图片生成失败：' + (generateResponse.reason?.message || '请重试'))
    }

    // 如果两个操作都成功
    if (optimizeResponse.status === 'fulfilled' && optimizeResponse.value.success &&
        generateResponse.status === 'fulfilled' && generateResponse.value.success) {
      ElMessage.success('优化提示词和生成图片都成功完成！')
    }

  } catch (error) {
    console.error('Optimize and generate role error:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    roleOptimizingAndGenerating.value = false
  }
}

// 为编辑对话框优化并生成角色图片
const handleOptimizeAndGenerateRoleForEdit = async () => {
  if (!editRoleForm.roleName) {
    ElMessage.warning('请先填写角色名称')
    return
  }
  if (!editRoleForm.text_model_id) {
    ElMessage.warning('请先选择文本模型')
    return
  }
  if (!editRoleForm.img_model_id) {
    ElMessage.warning('请先选择图片模型')
    return
  }
  if (!editRoleForm.prompt_id) {
    ElMessage.warning('请先选择提示词模板')
    return
  }

  try {
    roleOptimizingAndGenerating.value = true
    ElMessage.info('正在同时优化提示词和生成图片，请耐心等待...')

    const requestData = {
      prompt_id: editRoleForm.prompt_id,
      text_model_id: editRoleForm.text_model_id,
      img_model_id: editRoleForm.img_model_id,
      role_name: editRoleForm.roleName,
      role_detail: editRoleForm.roleDetail,
      role_dress: editRoleForm.roleDress,
      role_prompt: editRoleForm.rolePromt,
      role_img: editRoleForm.roleImg,
      ref_img: editRoleForm.refImg
    }

    // 同时调用优化提示词和生成图片接口
    const [optimizeResponse, generateResponse] = await Promise.allSettled([
      optimizeRolePrompt(requestData),
      editRoleForm.refImg
        ? generateRoleImageWithReference(
            editRoleForm.img_model_id,
            editRoleForm.rolePromt,
            editRoleForm.refImg.split(',')[0] || null,
            editRoleForm.refImg.split(',')[1] || null,
            editRoleForm.refImg.split(',')[2] || null
          )
        : generateRoleImage(editRoleForm.img_model_id, editRoleForm.rolePromt)
    ])

    // 处理优化提示词的结果
    if (optimizeResponse.status === 'fulfilled' && optimizeResponse.value.success) {
      editRoleForm.rolePromt = optimizeResponse.value.optimizedPrompt
      ElMessage.success('AI优化成功！')
    } else if (optimizeResponse.status === 'rejected') {
      console.error('AI optimize error:', optimizeResponse.reason)
      ElMessage.warning('AI优化失败，但图片生成继续进行')
    }

    // 处理生成图片的结果
    if (generateResponse.status === 'fulfilled' && generateResponse.value.success) {
      const imageUrl = generateResponse.value.localUrl || generateResponse.value.imageUrl
      if (imageUrl) {
        editRoleForm.roleImg = imageUrl
        ElMessage.success('图片生成成功！')
      } else {
        ElMessage.error('图片生成失败：未返回有效的图片URL')
      }
    } else if (generateResponse.status === 'rejected') {
      console.error('Generate image error:', generateResponse.reason)
      ElMessage.error('图片生成失败：' + (generateResponse.reason?.message || '请重试'))
    }

    // 如果两个操作都成功
    if (optimizeResponse.status === 'fulfilled' && optimizeResponse.value.success &&
        generateResponse.status === 'fulfilled' && generateResponse.value.success) {
      ElMessage.success('优化提示词和生成图片都成功完成！')
    }

  } catch (error) {
    console.error('Optimize and generate role for edit error:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    roleOptimizingAndGenerating.value = false
  }
}

// 提取章节文字
const handleExtractChapterText = async () => {
  if (!selectedChapter.value) {
    ElMessage.warning('请先选择一个章节')
    return
  }
  if (!selectedChapter.value.filePath) {
    ElMessage.warning('该章节没有上传文档')
    return
  }

  try {
    extracting.value = true
    ElMessage.info('正在提取文字...')

    const response = await extractDocxText(selectedChapter.value.filePath)
    if (response.code === 200 && response.data) {
      generationForm.content = response.data
      ElMessage.success('文字提取成功')
    } else {
      ElMessage.error('文字提取失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('Extract text error:', error)
    ElMessage.error('文字提取失败：' + (error.message || '请重试'))
  } finally {
    extracting.value = false
  }
}

// 优化分镜提示词
const handleOptimizeStoryPrompt = async () => {
  if (!generationForm.content) {
    ElMessage.warning('请先提取章节文字')
    return
  }
  if (!generationForm.text_model_id) {
    ElMessage.warning('请选择文本模型')
    return
  }
  if (!generationForm.prompt_id) {
    ElMessage.warning('请选择提示词模板')
    return
  }

  try {
    optimizingStoryPrompt.value = true
    ElMessage.info('AI正在优化提示词，请耐心等待...')

    const requestData = {
      text_model_id: generationForm.text_model_id,
      prompt_id: generationForm.prompt_id,
      content: generationForm.content,
      storyPrompt: generationForm.storyPrompt,
      novelId: novelId.value,
      chapterId: selectedChapter.value?.id
    }

    const response = await optimizeStoryPrompt(requestData)
    if (response.success) {
      // optimizedPrompt返回的就是JSON数据，直接解析
      parseStoryboardJson(response.optimizedPrompt)

      // 将JSON美化后显示在提示词输入框
      try {
        const parsed = JSON.parse(response.optimizedPrompt)
        generationForm.storyPrompt = JSON.stringify(parsed, null, 2)
      } catch (e) {
        generationForm.storyPrompt = response.optimizedPrompt
      }

      storyboardPrompt.value = response.optimizedPrompt
      ElMessage.success('AI优化成功！已生成分镜np')
    } else {
      ElMessage.error('AI优化失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('AI optimize error:', error)
    ElMessage.error('AI优化失败：' + (error.message || '请重试'))
  } finally {
    optimizingStoryPrompt.value = false
  }
}

// 生成分镜
const handleGenerateStoryboard = async () => {
  if (!generationForm.content) {
    ElMessage.warning('请先提取章节文字')
    return
  }
  if (!generationForm.storyPrompt) {
    ElMessage.warning('请填写或优化分镜提示词')
    return
  }
  if (!generationForm.text_model_id) {
    ElMessage.warning('请选择文本模型')
    return
  }
  if (!generationForm.prompt_id) {
    ElMessage.warning('请选择提示词模板')
    return
  }

  try {
    generatingStoryboard.value = true
    ElMessage.info('正在生成分镜JSON，请耐心等待...')

    const requestData = {
      content: generationForm.content,
      text_model_id: generationForm.text_model_id,
      prompt_id: generationForm.prompt_id,
      storyPrompt: generationForm.storyPrompt,
      novelId: novelId.value,
      chapterId: selectedChapter.value?.id
    }

    const response = await generateStoryboard(requestData)
    if (response.code === 200 && response.data) {
      generationResult.value = response.data
      // 解析JSON并提取分镜
      parseStoryboardJson(response.data)
      ElMessage.success('分镜JSON生成成功！')
    } else {
      ElMessage.error('分镜生成失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    console.error('Generate storyboard error:', error)
    ElMessage.error('分镜生成失败：' + (error.message || '请重试'))
  } finally {
    generatingStoryboard.value = false
  }
}

// 解析JSON并提取分镜数据
const parseStoryboardJson = (jsonString) => {
  try {
    // 去除markdown代码块标记
    let cleanedJson = jsonString.trim()
    if (cleanedJson.startsWith('```json')) {
      cleanedJson = cleanedJson.replace(/^```json\n?/, '').replace(/\n?```$/, '')
    } else if (cleanedJson.startsWith('```')) {
      cleanedJson = cleanedJson.replace(/^```\n?/, '').replace(/\n?```$/, '')
    }

    const parsed = JSON.parse(cleanedJson)

    if (parsed.scenes && Array.isArray(parsed.scenes)) {
      parsedStoryboards.value = parsed.scenes.map(scene => ({
        ...scene,
        image: '',
        imagePrompt: '',
        optimizing: false,
        generating: false,
        characters_list: []
      }))

      // 自动匹配每个分镜的人物
      parsedStoryboards.value.forEach(storyboard => {
        if (storyboard.characters_in_scene) {
          matchCharacters(storyboard)
        }
      })
    } else {
      ElMessage.warning('JSON格式不正确，未找到scenes数组')
      parsedStoryboards.value = []
    }
  } catch (error) {
    console.error('Parse JSON error:', error)
    ElMessage.error('JSON解析失败：' + error.message)
    parsedStoryboards.value = []
  }
}

// 编辑分镜
const editStoryboard = (storyboard) => {
  ElMessage.info('编辑功能开发中...')
}

// 匹配人物
const matchCharacters = (storyboard) => {
  if (!storyboard.characters_in_scene) {
    storyboard.characters_list = []
    return
  }

  // 处理出场人物，可能是字符串或数组
  let characterNames = []
  if (Array.isArray(storyboard.characters_in_scene)) {
    // 如果是数组，直接使用
    characterNames = storyboard.characters_in_scene.filter(name => name && name.trim())
  } else if (typeof storyboard.characters_in_scene === 'string') {
    // 如果是字符串，按逗号分隔
    characterNames = storyboard.characters_in_scene
        .split(',')
        .map(name => name.trim())
        .filter(name => name)
  } else {
    storyboard.characters_list = []
    return
  }

  if (characterNames.length === 0) {
    storyboard.characters_list = []
    return
  }

  // 为每个人物查找匹配的角色
  storyboard.characters_list = characterNames.map(name => {
    // 在角色列表中查找完全匹配或包含该姓名的人物
    const matchedRole = roles.value.find(role =>
        role.roleName === name || role.roleName.includes(name)
    )

    if (matchedRole) {
      // 找到匹配的角色
      return {
        name: name,
        matched: true,
        id: matchedRole.id,
        image: matchedRole.roleImg || '',
        roleDetail: matchedRole.roleDetail || '',
        roleDress: matchedRole.roleDress || ''
      }
    } else {
      // 未找到匹配的角色
      return {
        name: name,
        matched: false,
        image: ''
      }
    }
  })
}

// 创建新角色
const createNewCharacter = (characterName, storyboard, index) => {
  // 设置默认表单值
  roleForm.novelId = novelId.value
  roleForm.roleName = characterName
  roleForm.roleDetail = ''
  roleForm.roleDress = ''
  roleForm.rolePromt = ''
  roleForm.roleImg = ''
  roleForm.refImg = ''
  roleForm.text_model_id = generationForm.text_model_id
  roleForm.img_model_id = generationForm.img_model_id
  roleForm.prompt_id = generationForm.prompt_id

  // 清除表单验证
  if (roleFormRef.value) {
    roleFormRef.value.clearValidate()
  }

  // 标记当前要创建的角色
  creatingCharacterStoryboard = { storyboard, index, characterName }

  showAddRoleDialog.value = true
}

// 上传人物图片
const uploadCharacterImage = (char, storyboard, index) => {
  // 这里可以实现图片上传功能
  ElMessage.info('图片上传功能开发中...')
}

// 保存角色后自动更新分镜中的人物信息
let creatingCharacterStoryboard = null

// 优化单个分镜的图片提示词
const optimizeScenePrompt = async (storyboard) => {
  if (!generationForm.text_model_id) {
    ElMessage.warning('请先在生成分镜时选择文本模型')
    return
  }

  if (!generationForm.prompt_id) {
    ElMessage.warning('请先在生成分镜时选择提示词模板')
    return
  }

  try {
    storyboard.optimizing = true
    ElMessage.info(`正在优化分镜 #${storyboard.id} 的提示词...`)

    // 构建分镜信息字符串
    let content = [
      `分镜ID: ${storyboard.id}`,
      `分镜大小: ${storyboard.size}`,
      `构图: ${storyboard.position}`,
      `表情: ${storyboard.expression}`,
      `对话: ${storyboard.dialogue}`,
      `描述: ${storyboard.description}`,
      `场景人物: ${Array.isArray(storyboard.characters_in_scene)
          ? storyboard.characters_in_scene.join(', ')
          : storyboard.characters_in_scene}`
    ].join('\n')

    // 如果有角色信息，添加到content
    if (storyboard.characters_list && storyboard.characters_list.length > 0) {
      const matchedChars = storyboard.characters_list.filter(char => char.matched)
      if (matchedChars.length > 0) {
        content += '\n\n角色详情：\n'
        matchedChars.forEach(char => {
          content += `- ${char.name}`
          if (char.roleDetail) content += ` (${char.roleDetail})`
          if (char.roleDress) content += ` - ${char.roleDress}`
          content += '\n'
        })
      }
    }

    const response = await optimizeStoryImgPrompt({
      text_model_id: generationForm.text_model_id,
      prompt_id: generationForm.prompt_id,
      content: content
    })

    if (response.success) {
      // 更新分镜的图片生成提示词
      if (response.optimizedPrompt) {
        storyboard.imagePrompt = response.optimizedPrompt
        ElMessage.success('提示词优化成功！')
      } else {
        ElMessage.warning('提示词优化成功，但未返回优化后的内容')
      }
    } else {
      ElMessage.error('提示词优化失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('Optimize scene prompt error:', error)
    ElMessage.error('提示词优化失败：' + (error.message || '请重试'))
  } finally {
    storyboard.optimizing = false
  }
}

// 生成分镜图片
const generateSceneImage = async (storyboard) => {
  if (!generationForm.img_model_id) {
    ElMessage.warning('请先在生成分镜时选择图片模型')
    return
  }

  // 构建图片生成提示词
  // 如果已经优化过提示词，优先使用优化后的
  let imagePrompt = storyboard.imagePrompt || `${storyboard.description}\n人物: ${storyboard.characters_in_scene}\n表情: ${storyboard.expression}\n构图: ${storyboard.position}`

  // 收集参考图片
  let referenceImages = []

  // 优先使用分镜的参考图片
  if (storyboard.referenceImage) {
    referenceImages.push(getImageUrl(storyboard.referenceImage))
  }

  // 如果有角色图片，也加入参考
  if (storyboard.characters_list && storyboard.characters_list.length > 0) {
    const matchedChars = storyboard.characters_list.filter(char => char.matched && char.image)

    if (matchedChars.length > 0) {
      // 添加角色描述
      const characterDetails = matchedChars.map(char => {
        let detail = char.name
        if (char.roleDetail) detail += ` - ${char.roleDetail}`
        if (char.roleDress) detail += `，${char.roleDress}`
        return detail
      }).join('\n')
      imagePrompt += `\n\n角色详情：\n${characterDetails}`

      // 收集角色图片作为参考
      const characterImages = matchedChars.map(char => getImageUrl(char.image)).filter(url => url)
      referenceImages = [...referenceImages, ...characterImages]
    }
  }

  try {
    storyboard.generating = true
    ElMessage.info(`正在为分镜 #${storyboard.id} 生成图片...`)

    // 生成图片
    let response
    if (referenceImages.length > 0) {
      // 使用带参考图片的接口
      response = await generateRoleImageWithReference(
          generationForm.img_model_id,
          imagePrompt,
          referenceImages[0] || null,
          referenceImages[1] || null,
          referenceImages[2] || null
      )
    } else {
      // 没有参考图片，使用普通接口
      response = await generateRoleImage(
          generationForm.img_model_id,
          imagePrompt
      )
    }

    if (response.success) {
      const imageUrl = response.localUrl || response.imageUrl
      if (imageUrl) {
        storyboard.image = imageUrl
        ElMessage.success('图片生成成功！')
      } else {
        ElMessage.error('图片生成失败：未返回有效的图片URL')
      }
    } else {
      ElMessage.error('图片生成失败：' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('Generate scene image error:', error)
    ElMessage.error('图片生成失败：' + (error.message || '请重试'))
  } finally {
    storyboard.generating = false
  }
}

// 批量优化所有分镜的提示词
const optimizeAllScenePrompts = async () => {
  if (!generationForm.text_model_id) {
    ElMessage.warning('请先在生成分镜时选择文本模型')
    return
  }

  if (!generationForm.prompt_id) {
    ElMessage.warning('请先在生成分镜时选择提示词模板')
    return
  }

  if (!parsedStoryboards.value || parsedStoryboards.value.length === 0) {
    ElMessage.warning('没有可优化的分镜')
    return
  }

  try {
    optimizingAllPrompts.value = true
    ElMessage.info(`开始优化 ${parsedStoryboards.value.length} 个分镜的提示词...`)

    // 为每个分镜匹配人物信息
    for (const storyboard of parsedStoryboards.value) {
      if (!storyboard.characters_in_scene) continue
      matchCharacters(storyboard)
    }

    // 并发优化所有分镜的提示词
    const optimizePromises = parsedStoryboards.value.map(async (storyboard) => {
      try {
        // 构建分镜信息字符串
        let content = [
          `分镜ID: ${storyboard.id}`,
          `分镜大小: ${storyboard.size}`,
          `构图: ${storyboard.position}`,
          `表情: ${storyboard.expression}`,
          `对话: ${storyboard.dialogue}`,
          `描述: ${storyboard.description}`,
          `场景人物: ${Array.isArray(storyboard.characters_in_scene)
              ? storyboard.characters_in_scene.join(', ')
              : storyboard.characters_in_scene}`
        ].join('\n')

        // 添加角色详情
        if (storyboard.characters_list && storyboard.characters_list.length > 0) {
          const matchedChars = storyboard.characters_list.filter(char => char.matched)
          if (matchedChars.length > 0) {
            content += '\n\n角色详情：\n'
            matchedChars.forEach(char => {
              content += `- ${char.name}`
              if (char.roleDetail) content += ` (${char.roleDetail})`
              if (char.roleDress) content += ` - ${char.roleDress}`
              content += '\n'
            })
          }
        }

        const response = await optimizeStoryImgPrompt({
          text_model_id: generationForm.text_model_id,
          prompt_id: generationForm.prompt_id,
          content: content
        })

        if (response.success && response.optimizedPrompt) {
          storyboard.imagePrompt = response.optimizedPrompt
          return { success: true, storyboardId: storyboard.id }
        } else {
          console.error(`分镜 #${storyboard.id} 优化失败:`, response.message)
          return { success: false, storyboardId: storyboard.id }
        }
      } catch (error) {
        console.error(`优化分镜 #${storyboard.id} 失败:`, error)
        return { success: false, storyboardId: storyboard.id }
      }
    })

    // 等待所有优化请求完成
    const results = await Promise.allSettled(optimizePromises)
    const successCount = results.filter(r => r.status === 'fulfilled' && r.value.success).length

    ElMessage.success(`优化完成！成功优化 ${successCount}/${parsedStoryboards.value.length} 个分镜`)
  } catch (error) {
    console.error('Batch optimize prompts error:', error)
    ElMessage.error('批量优化失败：' + (error.message || '请重试'))
  } finally {
    optimizingAllPrompts.value = false
  }
}

// 保存所有分镜
const saveAllStoryboards = async () => {
  if (!parsedStoryboards.value || parsedStoryboards.value.length === 0) {
    ElMessage.warning('没有可保存的分镜')
    return
  }

  try {
    savingStoryboards.value = true
    ElMessage.info('开始保存分镜...')

    // 保存当前选中的章节ID
    const chapterId = selectedChapter.value?.id

    for (let i = 0; i < parsedStoryboards.value.length; i++) {
      const storyboard = parsedStoryboards.value[i]

      try {
        ElMessage.info(`正在保存分镜 ${i + 1}/${parsedStoryboards.value.length}...`)

        // 收集角色图片信息
        let characterImageInfo = ''
        if (storyboard.characters_list && storyboard.characters_list.length > 0) {
          const matchedChars = storyboard.characters_list.filter(char => char.matched && char.image)
          if (matchedChars.length > 0) {
            const referenceImages = matchedChars.map(char => getImageUrl(char.image)).filter(url => url)
            if (referenceImages.length > 0) {
              characterImageInfo = `\n\n[角色参考图片: ${referenceImages.length}张]`
            }
          }
        }

        // 准备保存数据 - 根据后端NovelStoryboard实体类字段
        const storyboardData = {
          novelId: novelId.value,
          name: `分镜 ${storyboard.id}`,
          novelChapter: chapterId,
          refRole: Array.isArray(storyboard.characters_in_scene)
              ? storyboard.characters_in_scene.join(',')
              : storyboard.characters_in_scene,
          prompt: storyboard.imagePrompt || `${storyboard.description}\n人物: ${storyboard.characters_in_scene}\n表情: ${storyboard.expression}\n构图: ${storyboard.position}`,
          img: storyboard.referenceImage || '',  // 参考图片
          res_img: storyboard.image || ''        // 最终生成的分镜图片
        }

        // 保存分镜的JSON数据到prompt_json字段
        // 确保所有字段都被正确保存
        const promptJsonData = {
          id: storyboard.id || '',
          size: storyboard.size || '',                    // 画格大小
          position: storyboard.position || '',            // 位置构图
          expression: storyboard.expression || '',        // 表情神态
          dialogue: storyboard.dialogue || '',            // 对话台词
          description: storyboard.description || '',      // 场景描述
          characters_in_scene: storyboard.characters_in_scene || '',  // 出场人物
          imagePrompt: storyboard.imagePrompt || ''       // 图片提示词
        }
        storyboardData.promptJson = JSON.stringify(promptJsonData)

        // 打印调试信息
        console.log('保存分镜JSON数据:', promptJsonData)

        // 添加角色图片信息到提示词
        if (characterImageInfo) {
          storyboardData.prompt += characterImageInfo
        }

        // 调用保存接口
        const response = await addStoryboard(storyboardData)

        if (response.code === 200) {
          ElMessage.success(`分镜 #${storyboard.id} 保存成功`)
        } else {
          ElMessage.warning(`分镜 #${storyboard.id} 保存失败: ${response.msg}`)
        }
      } catch (error) {
        console.error(`保存分镜 #${storyboard.id} 失败:`, error)
        ElMessage.warning(`分镜 #${storyboard.id} 保存失败`)
      }
    }

    ElMessage.success('所有分镜保存完成！')

    // 保存完成后刷新页面，重新加载分镜数据（因为后端会保存img参考图片）
    if (selectedChapter.value) {
      await loadChapterStoryboards(selectedChapter.value.id)
    }

  } catch (error) {
    console.error('Save storyboards error:', error)
    ElMessage.error('保存分镜失败：' + (error.message || '请重试'))
  } finally {
    savingStoryboards.value = false
  }
}

// 清空生成表单
const clearGenerationForm = () => {
  generationForm.content = ''
  generationForm.text_model_id = null
  generationForm.prompt_id = null
  generationForm.img_model_id = null
  generationForm.storyPrompt = ''
  storyboardPrompt.value = ''
  generationResult.value = ''
  parsedStoryboards.value = []
  ElMessage.success('已清空')
}

// 复制结果
const copyResult = () => {
  if (!generationResult.value) {
    ElMessage.warning('没有可复制的内容')
    return
  }
  navigator.clipboard.writeText(generationResult.value).then(() => {
    ElMessage.success('已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 清空结果
const clearResult = () => {
  generationResult.value = ''
  parsedStoryboards.value = []
  ElMessage.success('已清空结果')
}

// 批量生成图片
const batchGenerateImages = async () => {
  if (!generationForm.img_model_id) {
    ElMessage.warning('请先在生成分镜时选择图片模型')
    return
  }

  if (!parsedStoryboards.value || parsedStoryboards.value.length === 0) {
    ElMessage.warning('没有可生成图片的分镜')
    return
  }

  try {
    batchGeneratingImages.value = true
    ElMessage.info(`开始为 ${parsedStoryboards.value.length} 个分镜生成图片（排队处理）...`)

    // 顺序生成所有分镜的图片（因为有QPS限制）
    let successCount = 0
    for (let i = 0; i < parsedStoryboards.value.length; i++) {
      const storyboard = parsedStoryboards.value[i]

      try {
        ElMessage.info(`正在生成分镜 ${i + 1}/${parsedStoryboards.value.length} 的图片...`)

        // 构建图片生成提示词
        let imagePrompt = storyboard.imagePrompt || `${storyboard.description}\n人物: ${storyboard.characters_in_scene}\n表情: ${storyboard.expression}\n构图: ${storyboard.position}`

        // 收集参考图片
        let referenceImages = []

        // 优先使用分镜的参考图片
        if (storyboard.referenceImage) {
          referenceImages.push(getImageUrl(storyboard.referenceImage))
        }

        // 如果有角色图片，也加入参考
        if (storyboard.characters_list && storyboard.characters_list.length > 0) {
          const matchedChars = storyboard.characters_list.filter(char => char.matched && char.image)

          if (matchedChars.length > 0) {
            // 添加角色描述
            const characterDetails = matchedChars.map(char => {
              let detail = char.name
              if (char.roleDetail) detail += ` - ${char.roleDetail}`
              if (char.roleDress) detail += `，${char.roleDress}`
              return detail
            }).join('\n')
            imagePrompt += `\n\n角色详情：\n${characterDetails}`

            // 收集角色图片作为参考
            const characterImages = matchedChars.map(char => getImageUrl(char.image)).filter(url => url)
            referenceImages = [...referenceImages, ...characterImages]
          }
        }

        // 生成图片
        let response
        if (referenceImages.length > 0) {
          // 使用带参考图片的接口
          response = await generateRoleImageWithReference(
              generationForm.img_model_id,
              imagePrompt,
              referenceImages[0] || null,
              referenceImages[1] || null,
              referenceImages[2] || null
          )
        } else {
          // 没有参考图片，使用普通接口
          response = await generateRoleImage(
              generationForm.img_model_id,
              imagePrompt
          )
        }

        if (response.success) {
          const imageUrl = response.localUrl || response.imageUrl
          if (imageUrl) {
            storyboard.image = imageUrl
            successCount++
          }
        }
      } catch (error) {
        console.error(`生成分镜 #${storyboard.id} 图片失败:`, error)
      }
    }

    ElMessage.success(`批量生成完成！成功生成 ${successCount}/${parsedStoryboards.value.length} 个分镜图片`)
  } catch (error) {
    console.error('Batch generate images error:', error)
    ElMessage.error('批量生成图片失败：' + (error.message || '请重试'))
  } finally {
    batchGeneratingImages.value = false
  }
}

// 监听标签页切换，切换到生成记录时加载分镜数据
watch(activeTab, async (newTab) => {
  if (newTab === 'generation' && selectedChapter.value) {
    // 切换到生成记录标签页时，如果已选择章节，则加载该章节的分镜数据
    await loadChapterStoryboards(selectedChapter.value.id)
  }
})

// 页面加载
onMounted(() => {
  loadNovelInfo()
  loadChapters()
  loadRoles()
  loadModelAndPromptOptions()
})
</script>

<style lang="scss" scoped>
.novel-detail-container {
  min-height: 100vh;
  background-color: #f8f9fa;
}

// 顶部导航栏
.top-navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 64px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;

  .navbar-left {
    .logo {
      font-size: 24px;
      font-weight: bold;
      color: #409eff;
    }
  }

  .navbar-center {
    .nav-links {
      display: flex;
      gap: 32px;

      .nav-link {
        text-decoration: none;
        color: #000;
        font-weight: 500;
        transition: color 0.3s;

        &.active {
          color: #409eff;
        }

        &:hover {
          color: #409eff;
        }
      }
    }
  }

  .navbar-right {
    display: flex;
    align-items: center;
    gap: 16px;

    .nav-icon {
      font-size: 20px;
      color: #000;
      cursor: pointer;
    }
  }
}

// 主内容区域
.main-content {
  padding: 24px;
  max-width: 1500px;
  margin: 0 auto;
}

// 标签页导航
.tab-navigation {
  margin-bottom: 24px;

  .tab-list {
    display: flex;
    border-bottom: 1px solid #e4e7ed;

    .tab-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 12px 24px;
      cursor: pointer;
      color: #000;
      font-weight: 500;
      border-bottom: 2px solid transparent;
      transition: all 0.3s;

      .tab-icon {
        font-size: 16px;
      }

      &.active {
        color: #409eff;
        border-bottom-color: #409eff;
      }

      &:hover {
        color: #409eff;
      }
    }
  }
}

// 小说头部
.novel-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;

  .novel-title-section {
    .novel-title {
      font-size: 32px;
      font-weight: bold;
      color: #333;
      margin: 0 0 8px 0;
    }

    .novel-author {
      font-size: 16px;
      color: #000;
      margin: 0;
    }
  }

  .novel-actions {
    display: flex;
    align-items: center;
    gap: 16px;

    .back-link {
      color: #000;
      text-decoration: none;
      font-size: 14px;
      margin-right: 8px;

      &:hover {
        color: #409eff;
      }
    }

    .save-btn, .share-btn {
      border-radius: 8px;
      padding: 12px 24px;
      font-weight: 500;
    }
  }
}


// 内容区域
.content-area {
  display: flex;
  min-height: 600px;
  gap: 24px;
}

// 主内容区域
.main-content-area {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 24px;

  h3 {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    margin: 0 0 20px 0;
  }
}

// 章节管理区域
.chapter-management {
  width: 350px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  height: fit-content;
  margin-right: 24px;

  .chapter-actions {
    margin-bottom: 20px;

    .add-chapter-btn, .import-novel-btn {
      width: 100%;
      margin-bottom: 12px;
      border-radius: 8px;
    }
  }

  .chapter-list {
    h3 {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin: 0 0 16px 0;
    }

    .chapter-items {
      .chapter-item {
        display: flex;
        align-items: center;
        padding: 12px;
        border-radius: 6px;
        cursor: pointer;
        transition: background-color 0.3s;
        margin-bottom: 8px;

        &:hover {
          background-color: #f5f7fa;
        }

        &.active {
          background-color: #e6f7ff;
          border: 1px solid #409eff;
        }

        .chapter-drag-handle {
          margin-right: 8px;
          color: #999;
          cursor: grab;
        }

        .chapter-info {
          flex: 1;
          .chapter-title {
            font-size: 14px;
            color: #000;
          }
        }

        .chapter-actions {
          .more-icon {
            font-size: 16px;
            color: #000;
            cursor: pointer;
          }
        }
      }
    }
  }
}


// 目录标签页
.toc-tab {
  .chapter-table {
    .table-header {
      display: grid;
      grid-template-columns: 2fr 1fr 1fr 1fr;
      gap: 16px;
      padding: 12px;
      background: #f8f9fa;
      border-radius: 6px;
      font-weight: bold;
      color: #000;
      margin-bottom: 8px;
    }

    .table-row {
      display: grid;
      grid-template-columns: 2fr 1fr 1fr 1fr;
      gap: 16px;
      padding: 12px;
      border-bottom: 1px solid #e4e7ed;
      align-items: center;
      color: #000;

      &:hover {
        background: #f5f7fa;
      }

      .col-status {
        .status-tag {
          background-color: #f0f9ff !important;
          border-color: #67c23a !important;
          color: #67c23a !important;
        }
      }

      .col-actions {
        .edit-btn {
          background-color: #409eff !important;
          border-color: #409eff !important;
          color: #fff !important;

          &:hover {
            background-color: #66b1ff !important;
            border-color: #66b1ff !important;
          }
        }

        .delete-btn {
          background-color: #f56c6c !important;
          border-color: #f56c6c !important;
          color: #fff !important;

          &:hover {
            background-color: #f78989 !important;
            border-color: #f78989 !important;
          }
        }
      }
    }
  }
}

// 概览标签页
.overview-tab {
  .info-section {
    margin-bottom: 32px;

    h3 {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin: 0 0 16px 0;
    }

    .info-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;

      .info-item {
        display: flex;
        flex-direction: column;
        gap: 4px;

        label {
          font-size: 14px;
          color: #000;
          font-weight: 500;
        }

        span {
          font-size: 16px;
          color: #000;
        }
      }
    }
  }

  .stats-section {
    h3 {
      font-size: 16px;
      font-weight: bold;
      color: #333;
      margin: 0 0 16px 0;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 16px;

      .stat-card {
        text-align: center;
        padding: 20px;
        background: #f8f9fa;
        border-radius: 8px;

        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #409eff;
          margin-bottom: 8px;
        }

        .stat-label {
          font-size: 14px;
          color: #000;
        }
      }
    }
  }
}

// 人物管理标签页
.characters-tab {
  h3 {
    margin: 0;
  }

  .tab-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
  }

  .characters-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 24px;

    .character-card {
      background: white;
      border: 1px solid #e4e7ed;
      border-radius: 12px;
      padding: 20px;
      transition: all 0.3s;
      display: flex;
      flex-direction: column;
      align-items: center;

      &:hover {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        transform: translateY(-2px);
      }

      .character-avatar {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        overflow: hidden;
        margin-bottom: 16px;
        background: #f5f7fa;
        border: 3px solid #e4e7ed;
        flex-shrink: 0;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .default-avatar {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 32px;
          font-weight: bold;
          color: #409eff;
          background: #e6f7ff;
        }
      }

      .character-info {
        text-align: center;
        margin-bottom: 16px;
        width: 100%;
        flex-grow: 1;

        h4 {
          margin: 0 0 8px 0;
          font-size: 18px;
          font-weight: bold;
          color: #333;
        }

        .character-desc {
          margin: 0;
          color: #666;
          font-size: 14px;
          line-height: 1.5;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .character-actions {
        display: flex;
        gap: 8px;
        width: 100%;
        justify-content: center;
      }
    }
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    color: #999;

    .el-icon {
      font-size: 64px;
      margin-bottom: 16px;
      color: #d3d4d6;
    }

    p {
      font-size: 16px;
      margin: 0;
    }
  }
}


// 内容标签页
.content-tab {
  .chapter-content {
    h3 {
      margin-bottom: 20px;
    }

    .content-preview {
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      overflow: hidden;
    }

    .no-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 400px;
      color: #000;

      .el-icon {
        font-size: 48px;
        margin-bottom: 16px;
      }
    }
  }

  .no-chapter-selected {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 400px;
    color: #000;

    .el-icon {
      font-size: 48px;
      margin-bottom: 16px;
    }
  }
}

// 弹窗样式
:deep(.el-dialog) {
  .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #e4e7ed;

    .el-dialog__title {
      color: #333;
      font-weight: 600;
    }
  }

  .el-dialog__body {
    padding: 20px;
    color: #333;
  }

  .el-dialog__footer {
    padding: 10px 20px 20px;
    border-top: 1px solid #e4e7ed;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.form-tip {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

// 表单项标签颜色
:deep(.el-form-item__label) {
  color: #333 !important;
  font-weight: 500;
}

// 输入框文字颜色
:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  color: #333;
}

// 输入框占位符颜色
:deep(.el-input__inner::placeholder),
:deep(.el-textarea__inner::placeholder) {
  color: #999;
}

// 提示词输入框和按钮容器
.prompt-container {
  position: relative;
  width: 100%;

  .prompt-textarea {
    width: 100%;
    margin-bottom: 8px;
  }

  .prompt-buttons {
    display: flex;
    gap: 8px;
    justify-content: flex-end;
    margin-top: 8px;

    .el-button {
      font-size: 12px;
      padding: 8px 16px;
    }
  }
}

// 预览标签页
.preview-tab {
  .preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h3 {
      margin: 0;
      font-size: 20px;
      color: #303133;
    }

    .preview-header-right {
      display: flex;
      align-items: center;
      gap: 16px;

      span {
        color: #909399;
        font-size: 14px;
      }
    }
  }

  .preview-content {
    .no-chapter-selected,
    .no-storyboards {
      text-align: center;
      padding: 60px 20px;
      color: #909399;

      .el-icon {
        font-size: 60px;
        margin-bottom: 16px;
        color: #c0c4cc;
      }

      p {
        margin: 8px 0;
        font-size: 15px;
      }

      .hint {
        font-size: 13px;
        color: #c0c4cc;
      }
    }

    .storyboard-preview-list {
      display: flex;
      flex-direction: column;
      gap: 24px;
      max-width: 800px;
      margin: 0 auto;

      .preview-item {
        border: 1px solid #e4e7ed;
        border-radius: 12px;
        overflow: hidden;
        background: #fff;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

        &:hover {
          box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
          border-color: #409eff;
        }

        .preview-item-header {
          padding: 12px 16px;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          font-weight: 600;

          h4 {
            margin: 0;
            font-size: 14px;
          }
        }

        .preview-item-image {
          padding: 0;
          background: #fafbfc;
          display: flex;
          align-items: center;
          justify-content: center;

          img {
            width: 100%;
            height: auto;
            object-fit: contain;
            display: block;
          }

          .no-image-preview {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 80px 20px;
            color: #c0c4cc;
            width: 100%;
            min-height: 400px;

            .el-icon {
              font-size: 64px;
              margin-bottom: 12px;
            }

            p {
              margin: 0;
              font-size: 14px;
            }
          }
        }
      }
    }
  }
}

// 生成记录标签页
.generation-tab {
  h3 {
    margin: 0;
  }

  .generation-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
  }

  .generation-content {
    .el-form {
      .el-form-item {
        .result-actions {
          margin-top: 12px;
          display: flex;
          gap: 8px;
        }
      }
    }
  }

  // 分镜列表样式
  .storyboard-list {
    display: flex;
    flex-direction: column;
    gap: 24px;

    .storyboard-item {
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      padding: 16px;
      background: #fafbfc;

      .storyboard-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 2px solid #e4e7ed;

        h4 {
          margin: 0;
          font-size: 16px;
          color: #409eff;
          font-weight: 600;
        }
      }

      .storyboard-content {
        display: flex;
        gap: 20px;

        .storyboard-image {
          width: 300px;
          flex-shrink: 0;

          img {
            width: 100%;
            height: 400px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid #e4e7ed;
          }

          .no-image {
            width: 100%;
            height: 400px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: #f5f7fa;
            border-radius: 8px;
            border: 1px dashed #d3d4d6;
            color: #909399;

            .el-icon {
              font-size: 48px;
              margin-bottom: 12px;
            }

            p {
              margin: 0;
              font-size: 14px;
            }
          }

          .image-actions {
            margin-top: 12px;
            display: flex;
            justify-content: center;
          }
        }

        .reference-image {
          width: 200px;
          flex-shrink: 0;
          margin-left: 16px;

          h5 {
            margin: 0 0 8px 0;
            font-size: 14px;
            color: #606266;
            font-weight: 500;
          }

          img {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid #e4e7ed;
          }
        }

        .storyboard-info {
          flex: 1;

          .info-row {
            display: flex;
            align-items: center;
            margin-bottom: 12px;

            label {
              width: 100px;
              font-size: 14px;
              color: #606266;
              font-weight: 500;
              flex-shrink: 0;
            }

            .el-input,
            .el-textarea {
              flex: 1;
            }

          }

          .matched-characters {
            margin-top: 16px;
            padding-top: 16px;
            border-top: 1px solid #e4e7ed;

            label {
              display: block;
              font-size: 14px;
              color: #606266;
              font-weight: 500;
              margin-bottom: 12px;
            }

            .character-cards {
              display: flex;
              flex-wrap: wrap;
              gap: 12px;

              .character-card {
                display: flex;
                flex-direction: column;
                align-items: center;
                padding: 12px;
                border: 1px solid #e4e7ed;
                border-radius: 8px;
                background: white;
                transition: all 0.3s;
                min-width: 100px;

                &:hover {
                  border-color: #409eff;
                  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
                }

                .character-avatar {
                  width: 60px;
                  height: 60px;
                  border-radius: 50%;
                  overflow: hidden;
                  margin-bottom: 8px;
                  border: 2px solid #e4e7ed;

                  img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                  }

                  .default-avatar {
                    width: 100%;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background: #f5f7fa;
                    color: #409eff;
                    font-size: 24px;
                    font-weight: bold;
                  }
                }

                .character-name {
                  font-size: 13px;
                  color: #606266;
                  font-weight: 500;
                  text-align: center;
                  margin-bottom: 8px;
                  max-width: 100px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                }

                .character-actions {
                  width: 100%;

                  .el-button {
                    width: 100%;
                    font-size: 12px;
                    padding: 6px 8px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}


// 响应式设计
@media (max-width: 1400px) {
  .chapter-management {
    width: 320px;
  }
}

@media (max-width: 1200px) {
  .content-area {
    flex-direction: column;
  }

  .chapter-management {
    width: 100%;
    margin-right: 0;
    margin-bottom: 24px;
  }
}

@media (max-width: 768px) {
  .main-content {
    padding: 16px;
  }

  .novel-header {
    flex-direction: column;
    gap: 16px;
  }

  .novel-actions {
    width: 100%;
    justify-content: space-between;
  }

  .toc-tab {
    .chapter-table {
      .table-header, .table-row {
        grid-template-columns: 1fr;
        gap: 8px;
      }
    }
  }

  .preview-tab {
    .storyboard-preview-list {
      max-width: 100%;
      padding: 0 16px;

      .preview-item {
        border-radius: 8px;

        .preview-item-image {
          padding: 12px;

          img {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>
